package org.example.reentrantlock;

import lombok.extern.slf4j.Slf4j;
import org.example.utils.Sleeper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zhengdp
 * @Description 可重入锁的可打断特性测试
 * @Date 2022/10/30 20:15
 * @Created by zhengdp
 */
@Slf4j(topic = "c.InterruptTest")
public class InterruptTest {
    static ReentrantLock lock = new ReentrantLock();
    public static void main(String[] args) {
        Map<String,Integer> result = new HashMap<>();
        Thread t1 = new Thread(() -> {
            try{
                // 如果没有竞争，那么此方法就会获取到 Lock对象锁
                // 如果有竞争，就会进入阻塞队列。可以被其他线程用 interrupt 方法打断
                log.info("尝试获得锁");
             lock.lockInterruptibly();
            } catch (InterruptedException e) {
                e.printStackTrace();
                log.info("没有获取到锁");
                return;
            }
            try{
                log.info("获取到锁");
            }finally {
                lock.unlock();
            }
        },"t1");

        lock.lock();
        t1.start();
        Sleeper.sleep(1000);
        log.info("打断t1线程,使其不再等待");
        t1.interrupt();
    }

}
